package br.com.sig.presentation.scope;

import java.util.Map;

import javax.enterprise.context.spi.Context;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.faces.context.FacesContext;
import javax.inject.Named;

@Named
public class ViewContext<T> implements Context {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Class getScope() {
		return ViewScoped.class;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public  T get(Contextual contextual, CreationalContext creationalContext) {
		Bean bean = (Bean) contextual;
		Map viewMap = getViewMap();
		if(viewMap != null && viewMap.containsKey(bean.getName())) {
			return (T) viewMap.get(bean.getName());
		} else {
			T t = (T) bean.create(creationalContext);
			if (viewMap != null) {
				viewMap.put(bean.getName(), t);
			}
			return t;
		}
	}

	@SuppressWarnings("rawtypes")
	private Map getViewMap() {
		FacesContext fctx = FacesContext.getCurrentInstance();
		return fctx != null ? fctx.getViewRoot().getViewMap(true) : null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public  T get(Contextual contextual) {
		Bean bean = (Bean) contextual;
		Map viewMap = getViewMap();
		if(viewMap != null && viewMap.containsKey(bean.getName())) {
			return (T) viewMap.get(bean.getName());
		} else {
			return null;
		}
	}

	public boolean isActive() {
		return true;
	}
}